<?php
namespace app\common\model;

use app\common\service\LangMap;
use think\facade\Db;
use think\model\concern\SoftDelete;

class CouponModel extends BaseModel
{
    use SoftDelete;
    protected $table='coupon';

    public $lang = "zh";

    public static $fields_type = [
        ['name'=>'平台优惠券'],
        ['name'=>'特定优惠券'],
    ];

    public function getLocationAddrAttr($value){
        $province = $this['province'];
        $city = $this['city'];
        $area = $this['area'];
        $locationAddr = "";
        if(!empty($province)){
            $locationAddr .=$province.'/';
            if(!empty($city)){
                $locationAddr .=$city.'/';
            }
            if(!empty($area)){
                $locationAddr .=$area;
            }
        }
        return $locationAddr;
    }

    public function getLocationIntroAttr()
    {
        $location_addr = $this['location_addr'];
        if(empty($location_addr)){
            return '通用';
        }else{
            return $location_addr;
        }
    }

    public function getDayIntroAttr($value)
    {
        $expire_day = empty($this['expire_day'])?0:$this['expire_day'];
        if(!empty($expire_day) ){
            return '自领取'.$expire_day.'天内有效' ;
        }

        $start_date = $this['start_date'];
        $end_date = $this['end_date'];
        if(empty($start_date) || empty($end_date)){
            return '永久有效';
        }else{
            return $start_date.'~'.$end_date;
        }
    }

    public function getPayMoneyIntroAttr($value)
    {
        $pay_money = empty($this['pay_money'])?0:$this['pay_money'];
        return empty($pay_money) ? '直接优惠' : '满'.$pay_money.'立减';

    }

    public function getCouponIntroAttr($value)
    {
        $pay_money = empty($this['pay_money'])?0:$this['pay_money'];
        $money = empty($this['money'])?0:$this['money'];
        if(empty($pay_money)){
            $intro = '直接抵扣金额:'.$money.'元';//LangMap::getStr('attr_coupon_dic_dis_money',$this->lang,$money);
        }else{
            $intro = '满 '.$pay_money.' 立减 '.$money.' 元';//LangMap::getStr('attr_coupon_full_dis_money',$this->lang,$pay_money,$money);
        }
        return $intro;
    }

    public function getDisGoodsTagsAttr($value)
    {
//        $data = [];
//        $values = empty($value) ? [] : explode(",",$value) ;
//        foreach ($values as $item){
//            if(empty($item)) continue;
//            $data[] = intval($item);
//        }
        return empty($value)?'': mb_substr($value,1,-1);
    }

    public function getGetPerAttr($key)
    {
        return 0;
    }

    //获取过期事件
    public static function overDate($over_date)
    {
        if(empty($over_date)){
            return null;
        }
        return date('Y-m-d',strtotime('+ '.$over_date.'days',time()));
    }





    public static function handleSaveData(array $input_data = [])
    {
        $id = $input_data['id']??0;
//        if(empty($input_data['img'])) throw new \Exception('请上传图片');
        if(empty($input_data['code'])) throw new \Exception('请输入优惠券码');
        if(empty($input_data['name'])) throw new \Exception('请输入券名');
        if(empty($input_data['money'])) throw new \Exception('请输入优惠额度');

        if(!empty($input_data['money']) && $input_data['money']<0) throw new \Exception('用户优惠额度不得低于 0');
        if(!empty($input_data['full_money']) && $input_data['full_money']<0) throw new \Exception('用户满额度不得低于 0');
        $input_data['dis_goods_tags'] = !empty($input_data['dis_goods_tags']) ? ','.$input_data['dis_goods_tags'].',' : null;
        $locationAddr = empty($input_data['locationAddr'])?'':$input_data['locationAddr'];

        $input_data['goods'] = empty( $input_data['goods'])?null : $input_data['goods'];
        $locationAddr_arr = explode("/",$locationAddr);
        $input_data['province'] = $locationAddr_arr[0]??'';
        $input_data['city'] = $locationAddr_arr[1]??'';
        $input_data['area'] = $locationAddr_arr[2]??'';

        $start_date = empty($input_data['start_date']) ? null : $input_data['start_date'];
        $end_date = empty($input_data['end_date']) ? null : $input_data['end_date'];
        $input_data['start_date'] = $start_date;
        $input_data['end_date'] = $end_date;
        if ( (!empty($start_date) && empty($end_date)) || (empty($start_date) && !empty($end_date))){
            throw new \Exception('开始日期跟结束日必须同时设置');
        }
        if(!empty($end_date) && $end_date < $start_date){
            throw new \Exception('结束日期必须大于开始日期');
        }

        $check_where = [];
        $check_where[] = ['code','=',$input_data['code']];
        if(!empty($id)){
            $check_where[] = ['id','<>',$id];
        }
        $check_model = self::where($check_where)->find();
        if(!empty($check_model)) throw new \Exception('优惠码重复');


        (new self())->actionAdd($input_data);
    }


    /**
     * 发放优惠券
     * @param $input_data array
     * @throws
     * @return array
     * */
    public static function send(array $input_data = [])
    {
        $id = empty($input_data['id'])?0:$input_data['id'];
        $content = empty($input_data['content'])?[]: explode(',',$input_data['content']);
        $state = empty($input_data['state'])?0:$input_data['state'];
        if(empty($id))  throw new \Exception('参数异常:id');
        if($state==1 && empty($content))  throw new \Exception('请输入用户id');
        //优惠券信息
        $model_coupon = self::find($id);
        if(empty($model_coupon))  throw new \Exception('优惠券信息异常');
        if($model_coupon['status']!=1)  throw new \Exception('优惠券已被停用,无法进行发放');

        $over_date = self::overDate($model_coupon['expire_day']);
        $where = [];
        if($state==2){//全平台

        }else{
            //指定用户
            $where[] = ['id','in',$content];

        }
        //查找用户
        $record_content = $record_data = $sys_log = [];
        UserModel::where($where)->select()->each(function($item,$index)use($id,$model_coupon,$over_date,&$record_content, &$record_data,&$sys_log){
            array_push($record_content,(string)$item['id']);

            $start_date = $model_coupon['start_date'];
            $end_date = $model_coupon['end_date'];

            if(!empty($model_coupon['expire_day'])){
                $start_date = date('Y-m-d');
                $end_date = self::overDate($model_coupon['expire_day']);
            }

            $record_data_info = [
//                'no'=>self::make_coupon_card(),
                'uid'=>$item['id'],
                'cid'=>$id,
                'type'=>$model_coupon->getAttr('type'),
                'name'=>$model_coupon['name'],
//                'name_ban'=>(string)$model_coupon['name_ban'],
                'img'=>$model_coupon['img'],
                'money'=>$model_coupon['money'],
                'full_money'=>$model_coupon['full_money'],
                'content'=>$model_coupon['content'],
                'content_ban'=>$model_coupon['content_ban'],
                'start_date' => $start_date, //优惠券结束日期
                'over_date' => $end_date, //优惠券结束日期
                'goods' => $model_coupon['goods'], //可使用商品
                'province' => $model_coupon['province'], //
                'city' => $model_coupon['city'], //
                'area' => $model_coupon['area'], //
                'status' => 0,
                'create_time' => time(),
                'update_time' => time(),
            ];
            CouponUserModel::insert($record_data_info);
        });

        //数据取余
        $error_content = [];
        if($state!=2){
            $error_content = array_values(count($content)>count($record_content) ?array_diff($content,$record_content):array_diff($record_content,$content));
        }
        return [$record_content,$error_content,count($record_content)];

    }

    //获取项目可领取的优惠券
    public static function getProjectCoupon(array $input_data = [])
    {
        $project_id = $input_data['project_id'];
        $uid = $input_data['uid'];

        $where = [];
        $where[] = ['status','=',1];
        $where[] = ['reg_send','=',0];
        $with = [];
        if(!empty($uid)){
            $with['linkUserCoupon'] = function($query)use($uid){
                $query->where([['uid','=',$uid]]);
            };
        }
        $list = [];
        self::with($with)->where($where)->where(function($query)use($project_id){
            $query->whereRaw('find_in_set(goods, '.$project_id.')>0')->whereNull('goods','or');
        })->select()->each(function($item) use(&$list) {
            array_push($list,$item->apiNormalInfo());
        });
        return $list;

    }



    /**
     * 领取优惠券
     * @param UserModel $user_model
     * @param array $input_data
     * @throws
     */
    public static function getCoupon(UserModel $user_model, array $input_data=[])
    {
        $id = $input_data['id']??0;
        if(empty($id))  throw new \Exception( "参数异常:id");
        //优惠券信息
        $model_coupon = self::find($id);
        if(empty($model_coupon))  throw new \Exception( "优惠券信息异常" );
        if($model_coupon['status']!=1)  throw new \Exception( "该优惠券已停止领取" );


        //验证用户是否领取过
        $exist = CouponUserModel::where(['cid'=>$id,'uid'=>$user_model['id']])->find();
        if(!empty($exist))throw new \Exception( "已获得优惠券,无法再次领取" );
        //数量增加1
        if($model_coupon['num']>0){
            //增加使用数量
            $row_num = self::where([
                ['id','=',$id],
                ['use_num','=',$model_coupon['use_num']],
            ])->update(['use_num'=>Db::raw('use_num+1')]);
            if(!$row_num){
                throw new \Exception( "参与人数过多,请稍后尝试" );
            }
        }
        $start_date = $model_coupon['start_date'];
        $end_date = $model_coupon['end_date'];

        if(!empty($model_coupon['expire_day'])){
            $start_date = date('Y-m-d');
            $end_date = self::overDate($model_coupon['expire_day']);

        }
        $data = [
//            'no'=>self::make_coupon_card(),
            'uid'=>$user_model['id'],
            'cid'=>$id,
            'type'=>$model_coupon['type'],
            'name'=>$model_coupon['name'],
            'money'=>$model_coupon['money'],
            'full_money'=>$model_coupon['full_money'],
            'content'=>$model_coupon['content'],
            'goods' => $model_coupon['goods'], //可使用商品
            'province' => $model_coupon['province'], //
            'city' => $model_coupon['city'], //
            'area' => $model_coupon['area'], //
            'start_date' => $start_date, //优惠券结束日期
            'over_date' => $end_date, //优惠券结束日期
            'self_get' => 1,
            'status' => 0,
            'create_time' => time(),
            'update_time' => time(),
        ];
        try{
            CouponUserModel::insert($data);
        }catch (\Exception $e){

        }
    }


    /**
     * 获取数据
     * @param array $input_data 请求内容
     * @param int|null $limit 页面条数
     * @throws
     * @return \think\Paginator
     * */
    public static function getPageData(array $input_data=[])
    {
        $limit = $input_data['limit']??null;
        $activeState = $input_data['activeState']??null;
        $type = empty($input_data['type'])?0:$input_data['type'];
        $where = [];
        $where[] = ['type','=',$type];
        if(!empty($input_data['use_range'])){
            $where[] = ['use_range','=',$input_data['use_range']];
        }

        if(isset($input_data['code'])){
            $where[]=['code','=',$input_data['code']];
        }
        if(isset($input_data['status'])){
            $where[]=['status','=',$input_data['status']];
        }
        if(isset($input_data['id'])){
            $where[]=['id','=',$input_data['id']];
        }
        if(isset($input_data['reg_send'])){
            $where[]=['reg_send','=',$input_data['reg_send']];
        }
        $cid = $input_data['cid']??0;
        !empty($cid) && $where[] = ['cid','=',$cid];

        $uid = empty($input_data['uid']) ? 0 : $input_data['uid'];
        $keyword = empty($input_data['keyword']) ? '' : trim($input_data['keyword']);
        !empty($keyword) && $where[] = ['name','like','%'.$keyword.'%'];

//        dump($uid);exit;
        if(!empty($uid)){
            $model = self::with(['linkCouponCate','linkUserCoupon'=>function($query)use($uid){
                //自己手动领取
                $query->where(['uid'=>$uid,'self_get'=>1]);
            }])->where($where);

        }else{
            $model = self::with(['linkCouponCate'])->where($where);

        }

        $whereOr = [];
        if(isset($input_data['coupon']) && is_array($input_data['coupon'])){
            $whereOr[] = ['cid','=',0];
            $whereOr[] = ['id','in',$input_data['coupon']];
        }
        $model = $model->where(function($query)use($whereOr){
            $query->whereOr($whereOr);
        });
//        dump($where);exit;
        return $model->order('sort','asc')->paginate($limit);
    }

    /**
     * @param  int $id    优惠券id
     * @param  string $field
     * @throws
     * @return $model
     */
    public static function getDetails(int $id, $field='*')
    {
        $model = self::where(['status'=>1,'id'=>$id])->find();
        if(empty($model)) throw new \Exception('优惠券不存在');
        if($model['num']>0 && ($model['num']<=$model['use_num'])) throw new \Exception('优惠券可领取的次数不足');
        return $model;
    }

    public function apiFullInfo()
    {
        return array_merge($this->apiNormalInfo(),[
            'is_index'=>(int)$this['is_index'],
            'use_range'=>(int)$this['use_range'],
            'status'=>(int)$this['status'],
            'is_req'=>(int)$this['is_req'],
            'reg_send'=>(int)$this['reg_send'],
            'content'=>(string)$this['content'],
            'emails'=>(string)$this['emails'],
            'update_time'=>$this['update_time']
        ]);
    }


    public function apiNormalInfo()
    {
        $linkUserCoupon = $this->getRelation('linkUserCoupon');
        $linkCouponCate = $this->getRelation('linkCouponCate');
        return [
            'id' => $this['id'],
            'name' => $this['name'],
            'code' => (string)$this['code'],
//            'name_ban' => $this['name_ban'],
            'img' => $this['img'],
            'money' => $this['money'],
            'full_money' => $this['full_money'],
            'expire_day' => $this['expire_day'],
            'start_date' => $this['start_date'],
            'end_date' => $this['end_date'],
            'day_intro' => $this['day_intro'],
            'coupon_intro' => $this['coupon_intro'],
            'is_get' => empty($linkUserCoupon) || $linkUserCoupon->isEmpty() ? 0 : 1,
            'num' => (int)$this['num'],
            'get_per' => (string)$this['get_per'],
            'goods' => (string)$this['goods'],
            'dis_goods' => (string)$this['dis_goods'],
            'dis_goods_tags' => (string)$this['dis_goods_tags'],
            'location_addr'    => (string)$this['location_intro'],

            'cid' => (int)$linkCouponCate['id'],
            'cate_name' => (string)$linkCouponCate['name'],
//            'cate_name_ban' => (string)$linkCouponCate['name_ban'],
        ];
    }


    public function linkUserCoupon()
    {
        return $this->hasMany(CouponUserModel::class,'cid');
    }
    public function linkCouponCate()
    {
        return $this->belongsTo(CouponCateModel::class,'cid');
    }
}